<template>
    <el-form ref="ruleFormRef" style="width: 100%" :model="ruleForm" :rules="rules" label-width="auto" class="demo-ruleForm" :size="formSize" status-icon >
        <el-form-item label="使用日期" prop="pay_date">
            <el-date-picker v-model="ruleForm.pay_date" type="date" value-format="YYYY-MM-DD" placeholder="请选择日期" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="申请原因/用途" prop="reason">
            <el-input v-model="ruleForm.reason" />
        </el-form-item>
    </el-form>
    <div class="mt20 text-center">
        <el-button type="primary" @click="submitForm(ruleFormRef)" :loading="loading"> 保存 </el-button>
    </div>

</template>
  
<script lang="ts" setup>
import { reactive, ref,watch } from 'vue'
import { ElMessage, type ComponentSize, type FormInstance, type FormRules } from 'element-plus'
import http from '../util/request';
const loading = ref<boolean>(false)
interface RuleForm {
    source_id: number|string
    price: number|string
    reason: string
    type: string
    model: string
    source: string
    pay_date:string
} 
const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = ref<RuleForm>({
    source_id: 0,
    price:0,
    reason:'',
    type: '',
    source:'',
    model: '',
    pay_date:'',
})

const props = defineProps<{
    id:number|string
    price:number|string
    model:string
    source:string
    type:string
}>()

watch(props,()=>{
    ruleForm.value.source_id = props.id
    ruleForm.value.price = props.price
    ruleForm.value.reason = ''
    ruleForm.value.pay_date = ''
    ruleForm.value.source = props.source
    ruleForm.value.model = props.model
    ruleForm.value.type = props.type ?? 'finance' 
},{ immediate: true })

const rules = reactive<FormRules<RuleForm>>({
    reason: [
        { required: true, message: '请输入申请原因', trigger: 'blur' },
    ],
    
})

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            loading.value = true
            http.put('/approve',ruleForm.value).then((response:any)=>{
                loading.value = false
                if(response.data.code != 200){
                    ElMessage.error(response.data.msg);return
                }
                ElMessage.success(response.data.msg);
                onApplySave()  
            })
                      
        } else {
            console.log('error submit!', fields)
        }
    })
}

const onApplySave = () => {
    emit('onApplySave')
}

const emit = defineEmits(['onApplySave'])

</script>
<style scoped>
</style>
